import Vue from "vue";
import Vuex from "vuex";
import stu from "./stu/index";

import * as permissiApi from "@/api/permission";
import recursionRoutes from "@/utils/recursionRoutes";

import allRouters from "@/router/generateRouteArr";
import dynamicRoutes from "@/router/dynamicRoutes";
import router from "@/router";

import createPersistedState from "vuex-persistedstate";

Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    userMenu: [],
    userInfo: {},
    currentProduct: {}, //当前充值产品对象
    crumb: [],
  },
  getters: {},
  mutations: {
    SET_MENULIST(state, payload) {
      state.userMenu = [...payload];

      let homeRoute = dynamicRoutes.find((route) => route.path === "/");
      homeRoute.children = [...homeRoute.children, ...payload];
      router.addRoute(homeRoute);
    },
    SET_USERINFO(state, payload) {
      console.log(payload);
      state.userInfo = payload;
    },
    SET_CURRENT_PRODUCT(state, payload) {
      state.currentProduct = payload;
    },
    SET_CRUMB(state, payload) {
      state.crumb = payload;
    },
  },
  actions: {
    async FETCH_MENULIST(context, payload) {
      return permissiApi.getMenuList().then((res) => {
        let { menuList } = res.data;
        let userRoutes = recursionRoutes(allRouters[0].children, menuList);
        context.commit("SET_MENULIST", userRoutes);
      });
    },
  },
  modules: {
    stu,
  },
  plugins: [
    createPersistedState({
      Storage: window.localStorage,
      key: "qf2",
      paths: ["userInfo", "currentProduct"],
    }),
  ],
});
